/*
 * CHttpDownloader.cpp
 *
 *  Created on: 2017年7月26日
 *      Author: terry
 */

#include "CHttpDownloader.h"
#include "CHttpClient.h"
#include "TFileUtil.h"


CHttpDownloader::CHttpDownloader():
	m_url(),
	m_filepath(),
	m_sink()
{
	m_client.reset(new CHttpClient());
}

CHttpDownloader::~CHttpDownloader()
{
	close();
}


bool CHttpDownloader::download(const std::string& url, const std::string& filepath, const StringMap& headers, Sink* sink)
{
	if (url.empty() || filepath.empty())
	{
		printf("CHttpDownloader::download. invalid param.\n");
		return false;
	}

	if (m_client->isOpen())
	{
		printf("CHttpDownloader::download. client is already open.\n");
		return false;
	}

	m_url = url;
	m_filepath = filepath;
	m_sink = sink;

	m_client->get(url, headers, this);
	
	return true;
}

void CHttpDownloader::close()
{
	if (m_client)
	{
		m_client->close();
	}
}

void CHttpDownloader::handleResponse(int code, const char* body, size_t size)
{
	if (code == 200)
	{
		if (size > 0)
		{
			comn::FileUtil::write(body, size, m_filepath.c_str(), false);
		}
	}

	if (m_sink)
	{
		m_sink->onDownload(m_url, m_filepath, code);
	}
}